import { useInjectMap } from './hooks/use-inject-map'
import TileLayer from 'ol/layer/WebGLTile'
import GeoTIFF from 'ol/source/GeoTIFF'

export default defineComponent({
  name: 'GeoTiff',
  props: {
    data: Object
  },
  setup(props) {
    const { map } = useInjectMap()
    const layer = shallowRef()

    const addLayer = () => {
      layer.value = new TileLayer({
        source: undefined,
        style: {
          variables: {
            red: 1,
            redMax: 3000,
            green: 2,
            greenMax: 3000,
            blue: 3,
            blueMax: 3000
          },
          color: [
            'array',
            ['/', ['band', ['var', 'red']], ['var', 'redMax']],
            ['/', ['band', ['var', 'green']], ['var', 'greenMax']],
            ['/', ['band', ['var', 'blue']], ['var', 'blueMax']],
            6
          ]
        }
      })
      map?.addLayer(layer.value)
      if (props.data) {
        nextTick(() => {
          draw(props.data)
        })
      }
    }
    addLayer()

    const draw = (sourceData) => {
      const source = new GeoTIFF({
        normalize: false,
        wrapX: false,
        projection: 'EPSG:4326',
        ...sourceData
      })
      // 设置属性
      layer.value.setSource(source)
    }

    watch(
      () => props.data,
      (newwale) => {
        newwale && draw(newwale)
      },
      { immediate: true }
    )

    onBeforeUnmount(() => {
      map?.removeLayer(layer.value)
    })
    return {}
  },

  render() {
    return null
  }
})
